import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:qgchat/common/class/eventBus/index.dart';
import 'package:qgchat/common/class/overlay/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/wsAllGiftModel.dart';

///
/// 全局礼物播放组件
///

/// 动画时间
const Duration animationTime = Duration(milliseconds: 500);

/// 礼物显示持续时间
final Duration giftTime = Duration(milliseconds: 5000);

/// 礼物构造器
class GiftToast {
  static OverlayEntry overlayEntry; // 礼物视图
  static int count = 0; // 礼物总数
  static WsAllGiftModel _data; // 礼物模型
  static Timer timer; // 定时器
  static bool isDismiss = false;

  static show(WsAllGiftModel data) {
    if (_data?.name == data.name && _data?.id == data.id && timer.isActive) {
      print("礼物连击");
      count = count + data.number;
      bus.emit("doubleHit", count);
      timer?.cancel();
      timer = Timer(giftTime, () {
        dismiss();
      });
      return;
    }

    dismiss();
    count = data.number;

    _data = data;

    overlayEntry = OverlayEntry(builder: (context) {
      return GiftToastBuild(count, _data);
    });

    isDismiss = false;
    appOverlayState.insert(overlayEntry);
    timer = Timer(giftTime, () {
      dismiss();
    });
  }

  static dismiss() {
    if (!isDismiss) {
      timer?.cancel();
      overlayEntry?.remove();
      overlayEntry = null;
      isDismiss = true;
    }
  }
}

/// 礼物组件构造器
class GiftToastBuild extends StatefulWidget {
  GiftToastBuild(
    this.count,
    this.data, {
    Key key,
  }) : super(key: key);

  final int count;
  final WsAllGiftModel data;

  @override
  _GiftToastBuildState createState() => _GiftToastBuildState();
}

class _GiftToastBuildState extends State<GiftToastBuild>
    with TickerProviderStateMixin {
  // 出现动画
  Animation<double> animation;
  AnimationController controller;

  // 连击动画
  Animation<double> doubleHitA;
  AnimationController doubleHitC;

  int gitfCount;

  @override
  initState() {
    super.initState();
    showAnimation();
    doubleHitAnimation();
    doubleHitC.forward();

    gitfCount = widget.count;
    bus.on("doubleHit", (count) {
      if (mounted) {
        setState(() {
          gitfCount = count;
        });
        doubleHitC.reset();
        doubleHitC.forward();
      }
    });

    bus.on("giftQueue", (list) {
      print(list);
    });
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }

  // 出现动画
  showAnimation() {
    controller = AnimationController(
      duration: animationTime,
      vsync: this,
    );
    animation = CurvedAnimation(parent: controller, curve: Curves.easeOutBack);
    animation = Tween(begin: -100.0, end: 0.0).animate(animation)
      ..addListener(() {
        setState(() => {});
      });
    controller.forward();
  }

  // 连击动画
  doubleHitAnimation() {
    doubleHitC = AnimationController(
      duration: Duration(milliseconds: 300),
      vsync: this,
    );
    doubleHitA = CurvedAnimation(parent: doubleHitC, curve: Curves.ease);
    doubleHitA = Tween(begin: 0.3, end: 1.0).animate(doubleHitA)
      ..addListener(() {
        setState(() => {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          top: px(300),
          left: 0,
          child: Material(
            color: Colors.white.withOpacity(0),
            child: Container(
              child: Transform.translate(
                offset: Offset(animation.value, 0),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    // 主要内容 头像昵称等
                    // content(),
                    Container(
                      height: px(80),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                          bottomRight: Radius.circular(px(37)),
                          topRight: Radius.circular(px(37)),
                        ),
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            col('2becdd'),
                            col('24d4f2'),
                          ],
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black12,
                            offset: Offset(0.0, 15.0),
                            blurRadius: 15.0,
                            spreadRadius: 1.0,
                          ),
                        ],
                      ),
                      child: Stack(
                        overflow: Overflow.visible,
                        alignment: Alignment.centerRight,
                        children: [
                          Align(
                            child: Row(
                              children: [
                                avatar(),
                                name(),
                              ],
                            ),
                          ),
                          Positioned(
                            right: 0,
                            child: image(),
                          ),
                        ],
                      ),
                    ),
                    // 乘号
                    x,
                    // 数量
                    count(),
                  ],
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 主要内容 头像昵称等
  Widget content() {
    return Container(
      // width: px(413),
      height: px(102),
      decoration: BoxDecoration(
        // image: DecorationImage(
        //   image: AssetImage("assets/images/gitf-bg.png"),
        //   fit: BoxFit.contain,
        // ),
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            col('2becdd'),
            col('24d4f2'),
          ],
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          avatar(),
          name(),
          image(),
        ],
      ),
    );
  }

  /// 头像
  Widget avatar() {
    return Container(
      width: px(74),
      height: px(74),
      margin: EdgeInsets.only(
        left: px(20),
        right: px(15),
      ),
      child: ClipOval(
        child: CachedNetworkImage(
          imageUrl: "${widget.data.anchorHead}",
          fit: BoxFit.cover,
          errorWidget: (context, url, error) {
            return Config.errorNetImage;
          },
        ),
      ),
    );
  }

  /// 昵称和礼物名
  Widget name() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: px(5)),
      margin: EdgeInsets.only(right: px(120)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "主播 ${widget.data.anchorName} 收到",
            // "${widget.data.name} 送出${widget.data.giftname}",
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(26),
            ),
          ),
          Text(
            "${widget.data.name} 送出的 ${widget.data.giftname}",
            // "给主播：${widget.data.anchorName}",
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(20),
            ),
          ),
        ],
      ),
    );
  }

  /// 礼物图
  Widget image() {
    Widget icon;
    if (widget.data.icon != null) {
      icon = Image.network(
        "${widget.data.icon}",
        width: px(58),
        height: px(58),
        fit: BoxFit.contain,
      );
    } else {
      icon = Image.asset(
        "assets/images/icon/gift_bg.png",
        width: px(58),
        height: px(58),
        fit: BoxFit.contain,
      );
    }
    return Container(
      width: px(102),
      height: px(102),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(px(51)),
        color: col("f5f7fa"),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.1),
            blurRadius: 10.0,
          )
        ],
      ),
      child: icon,
    );
  }

  /// 乘号
  final Widget x = Container(
    margin: EdgeInsets.only(
      left: px(20),
      right: px(5),
    ),
    child: Image.asset(
      "assets/images/icon/x.png",
      width: px(19),
      height: px(19),
      fit: BoxFit.contain,
    ),
  );

  /// 礼物数量
  Widget count() {
    return Transform.scale(
      scale: doubleHitA.value,
      child: Row(
        children: gitfCount.toString().split('').map<Widget>((item) {
          return numImg(item);
        }).toList(),
      ),
    );
  }

  /// 数字图
  Widget numImg(String number) {
    return Image.asset(
      "assets/images/icon/$number.png",
      width: px(50),
      height: px(50),
      fit: BoxFit.contain,
    );
  }
}
